package com.example.controller;

import com.demo.utils.ResponseResult;
import com.demo.utils.ResultUtils;
import com.example.annotation.ResBodyLog;
import com.example.email.MailDto;
import com.example.redis.frequency.HttpFrequencyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

@RequestMapping("demo")
@RestController
@Slf4j
public class DemoController {

    @GetMapping("/send")
    @ResBodyLog
    public ResponseResult sendEmail(String author, String to, String text){
        HttpFrequencyUtils.isSend("/send");
        try {
            Thread.sleep(1000 * 2);
        } catch (InterruptedException e) {
            log.info(e.getMessage());
        }
        //发送邮件
        MailDto mailDto = new MailDto();
        mailDto.setTo(to);
        mailDto.setSubject("收到您朋友【"+author+"】的信件");
        mailDto.setText(text);
        return ResultUtils.success(mailDto);
    }

    @GetMapping("/timeOut/{seconds}")
    @ResBodyLog
    public ResponseResult timeOut(@PathVariable Integer seconds){
        FutureTask<String> task = new FutureTask(() -> {
            Thread.sleep(seconds * 1000);
            return "real time data";
        });
        try {
            new Thread(task).start();
            String result = task.get(6, TimeUnit.SECONDS);
            return ResultUtils.success(result);
        } catch (Exception e) {
            log.info(e.getMessage());
        }
        return ResultUtils.success("time out data");
    }
}
